package com.linxianqin.springbootVue.controller.system;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linxianqin.springbootVue.domain.constant.UserConstants;
import com.linxianqin.springbootVue.domain.convert.SysRoleConvert;
import com.linxianqin.springbootVue.domain.dto.SysRoleDTO;
import com.linxianqin.springbootVue.domain.entity.SysRole;
import com.linxianqin.springbootVue.domain.enums.BusinessType;
import com.linxianqin.springbootVue.domain.model.AjaxResult;
import com.linxianqin.springbootVue.domain.model.LoginUser;
import com.linxianqin.springbootVue.domain.page.TableDataInfo;
import com.linxianqin.springbootVue.domain.query.SysRoleQuery;
import com.linxianqin.springbootVue.domain.vo.SysRoleExcel;
import com.linxianqin.springbootVue.manage.annotation.SysLog;
import com.linxianqin.springbootVue.manage.core.BaseController;
import com.linxianqin.springbootVue.service.SysRoleService;
import com.linxianqin.springbootVue.service.SysUserService;
import com.linxianqin.springbootVue.service.webService.SysPermissionService;
import com.linxianqin.springbootVue.service.webService.TokenService;
import com.linxianqin.springbootVue.utils.SecurityUtils;
import com.linxianqin.springbootVue.utils.ServletUtils;
import com.linxianqin.springbootVue.utils.poi.ExcelUtil;
import com.linxianqin.springbootVue.utils.text.StringUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Api(value = "角色信息")
@Slf4j
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
    private final SysRoleService roleService;
    private final TokenService tokenService;
    private final SysPermissionService permissionService;
    private final SysUserService userService;
    public SysRoleController(SysRoleService roleService,TokenService tokenService,
                             SysPermissionService permissionService,SysUserService userService){
        this.roleService=roleService;
        this.tokenService=tokenService;
        this.permissionService=permissionService;
        this.userService=userService;
    }
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysRoleQuery query)
    {
        log.info("查询的信息：{}",query);
        //构建分页bean
        Page<SysRoleDTO> page = buildPage();
        //查询分页数据
        Page<SysRoleDTO> dtoPage = roleService.selectRolePage(page, query);
        return getDataTable(dtoPage);

    }

//    @SysLog(title = "角色管理", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('system:role:export')")
//    @GetMapping("/export")
//    public AjaxResult export()
//    {
//        List<SysRole> list = roleService.list();
//        //构建Excel工具包
//        ExcelUtil<SysRoleExcel> util = new ExcelUtil<>(SysRoleExcel.class);
//        //转化实体
//        List<SysRoleExcel> excelList = SysRoleConvert.INSTANCE.entity2Excel(list);
//        //序号id
//        for (int i = 0; i < excelList.size(); i++) {
//            excelList.get(i).setIndex(i+1);
//        }
//        return util.exportExcel(excelList, "角色数据");
//    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        return AjaxResult.success(SysRoleConvert.INSTANCE.entity2dto(roleService.getById(roleId)));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @SysLog(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRoleDTO roleDTO)
    {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(roleDTO)))
        {
            return AjaxResult.error("新增角色'" + roleDTO.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(roleDTO)))
        {
            return AjaxResult.error("新增角色'" + roleDTO.getRoleName() + "'失败，角色权限已存在");
        }
        roleDTO.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.insertRole(roleDTO));
    }
    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @SysLog(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRoleDTO roleDTO)
    {
        roleService.checkRoleAllowed(roleDTO);//校验角色是否允许操作
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(roleDTO)))
        {
            return AjaxResult.error("修改角色'" + roleDTO.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(roleDTO)))
        {
            return AjaxResult.error("修改角色'" + roleDTO.getRoleName() + "'失败，角色权限已存在");
        }
        roleDTO.setUpdateBy(SecurityUtils.getUsername());
        if (roleService.updateRole(roleDTO)) {
            // 更新缓存用户权限
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色'" + roleDTO.getRoleName() + "'失败，请联系管理员");
    }
    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @SysLog(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody  SysRoleDTO roleDTO)
    {
        roleService.checkRoleAllowed(roleDTO);
        return toAjax(roleService.authDataScope(roleDTO));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @SysLog(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRoleDTO roleDTO)
    {
        roleService.checkRoleAllowed(roleDTO);
        roleDTO.setUpdateBy(SecurityUtils.getUsername());
    return toAjax(roleService.updateById(SysRoleConvert.INSTANCE.dto2entity(roleDTO)));
    }
    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @SysLog(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable List<Long> roleIds)
    {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }
    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        List<SysRole> sysRoles = roleService.list();
        return AjaxResult.success(SysRoleConvert.INSTANCE.entity2dto(sysRoles));
    }
}
